package com.xszx.msm.controller;

import cn.hutool.core.util.RandomUtil;
import com.xszx.commonutils.R;
import com.xszx.msm.service.MsmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 白熊
 * @Date: 2024/7/23 19:26
 */
@RestController
@RequestMapping("/msm")
@Api(tags = "短信登录")
//@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ApiOperation("手机号接收验证码")
    @GetMapping(value = "/send/{phone}")
    public R code(@ApiParam(name = "phone",value = "手机号",required = true)
            @PathVariable("phone") String phone) {
        String pattern = "^1[3-9]\\d{9}$";   //正则表达式 手机号判断格式
        boolean b = phone.matches(pattern);
        if(!b){
            return R.error().message("请输入正确的手机号");
        }
        //将生成的验证码放入redis中, 键是手机号,值是验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return R.ok();

        //利用hutool生成随机的四位数的验证码
        code = RandomUtil.randomNumbers(4);
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);
        //模板CODE : SMS_470225047
        boolean isSend = msmService.send(phone, "SMS_470225047", param);
        if(isSend) {
            //键是手机号 值是验证码 5单位是分钟
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
//            Map map = new HashMap();
//            map.put("phone",phone);
//            map.put("code",code);
//            rabbitTemplate.convertAndSend("syx01",map);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }
    }
}
